import React, {Component} from 'react';
import './syle/index.less';
import cx from 'classnames';
import {Button, Icon, Menu} from 'antd';
import NavLink from "../Base/NavLink";
import Log from "../../utils";

const SubMenu = Menu.SubMenu;
const MenuItem = Menu.Item;

export default class LeftSideBar extends Component {

  constructor(props) {
    super(props);

    this.state = {
      openKeys: undefined,
      selectedKeys: undefined,
    };
  }

  static defaultProps = {
    theme: 'dark',
    locaPath: undefined,
    menuData:[],
  };

  componentWillMount() {
    const {locaPath} = this.props;
    this.changeMenu(locaPath);
  }

  componentWillReceiveProps(newProps) {
    const {locaPath} = newProps;
    this.changeMenu(locaPath);
  }

  // 改变menu选中状态
  changeMenu = (locaPath) => {
    if (!!locaPath) {
      if (locaPath.length == 1) {
        this.setState({selectedKeys: [locaPath[0]]});
      } else if (locaPath.length > 1) {
        this.setState({openKeys: [locaPath[0]], selectedKeys: [locaPath[1]]});
      }
    }
  }

  // 菜单展开关闭回调
  onOpenChange = (openKeys) => {

    if (openKeys.length > 1)
      openKeys.splice(0, openKeys.length - 1);
    this.setState({openKeys});

    Log.debug('菜单展开关闭回调', openKeys);
  }

  // 选中的菜单key
  onSelect = ({key}) => {
    Log.debug('onSelect', key);
    this.setState({selectedKeys: [key]});
  }

  getSubMenu = (menu, ppath) => {

    const {name, icon, path, children} = menu;

    return (
      <SubMenu key={path.slice(1, path.length)} title={<span><Icon type={icon}/><span>{name}</span></span>}>
        {this.getNavMenuItems(children, ppath + path)}
      </SubMenu>
    );
  }

  getMenuItem = (menu, ppath) => {
    const {name, path, icon} = menu;
    const title = !!icon ? <span><Icon type={icon}/><span>{name}</span></span> : name;
    return (
      <MenuItem key={path.slice(1, path.length)}>
        <NavLink target={ppath + path}
                 linkText={title}/>
      </MenuItem>
    );
  }

  getNavMenuItems = (menus, ppath = '') => {
    return menus.map(menu => {
      const {name, path, children} = menu;
      return (!!children ? this.getSubMenu(menu, ppath) : this.getMenuItem(menu, ppath));
    });
  }

  render() {

    let {openKeys, selectedKeys} = this.state;
    const {theme, menuData, hideSideBar} = this.props;

    Log.debug('hideSideBar', hideSideBar);

    const classnames = cx('sidebar-left', {[theme]: !!theme, 'open': !hideSideBar});
    return (
      <div className={classnames}>

        <div className="menu-content">
          <Menu
            mode="inline"
            onOpenChange={this.onOpenChange}
            theme={theme}
            inlineCollapsed={hideSideBar}
            openKeys={openKeys}
            onSelect={this.onSelect}
            selectedKeys={selectedKeys}
          >
            {this.getNavMenuItems(menuData)}
          </Menu>
        </div>
      </div>
    );
  }
}
